<template>
  <div style="padding: 50px;">
    <el-row :gutter="20">
      <el-col :span="8" >
        <el-card>
          <h3>消息推送（快捷创建）</h3>
          <el-form ref="form" :model="form" label-width="90px">
            <el-form-item label="通知标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入通知标题" />
            </el-form-item>
            <el-form-item label="通知内容">
              <el-input v-model="form.content" placeholder="请输入通知标题" type="textarea" />
            </el-form-item>
            <el-form-item label="接收人ID" prop="receiverId">
              <el-input v-model="form.receiverId" placeholder="请输入接收人ID" />
            </el-form-item>
            <el-form-item label="接收人昵称" prop="receiverName">
              <el-input v-model="form.receiverName" placeholder="请输入接收人昵称" />
            </el-form-item>
          </el-form>
          <div style="color: red;font-weight: 600;font-size: 14px;">PS：不填接受人id则视为群发</div>
          <el-button type="primary" @click="sendMessage" style="margin-top: 10px;">
            推送消息
          </el-button>

          <el-divider></el-divider>

          <div style="height: 300px; overflow-y: auto; border: 1px solid #ebeef5; padding: 10px;">
            <div v-for="(msg, index) in messages" :key="index" style="margin-bottom: 8px;">
              <el-tag type="info" size="small">消息 {{ index + 1 }}</el-tag>
              <span style="margin-left: 8px;">{{ msg }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="未读" name="unread">
              <el-row :gutter="20">
                <el-col :span="24" v-for="item in WbNoticeMessageList" :key="item.id">
                  <el-card class="notice-card">
                    <div class="card-header">
                      <span class="title">{{ item.title }}</span>
                      <!-- <el-tag type="danger" v-if="item.priority === '高'">高优先级</el-tag>
                      <el-tag type="info" v-else>普通</el-tag> -->
                      <el-tag type="success" v-if="item.isRead === 1">已读</el-tag>
                      <el-tag type="warning" v-else>未读</el-tag>
                    </div>
                    <div class="card-content">
                      <p>{{ item.content }}</p>
                      <small style="color: #ff6c37;">
                        <i class="el-icon-time"></i>
                        创建时间：{{ parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}') }}
                      </small>
                    </div>
                    <div class="card-actions">
                      <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-check"
                        @click="handleUpdateReadStatus(item)"
                        v-if="item.isRead === 0"
                      >设为已读</el-button>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
              <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
              />
            </el-tab-pane>

            <el-tab-pane label="已读" name="read">
              <el-row :gutter="20">
                <el-col :span="24" v-for="item in WbNoticeMessageList" :key="item.id">
                  <el-card class="notice-card">
                    <div class="card-header">
                      <span class="title">{{ item.title }}</span>
                      <el-tag type="success">已读</el-tag>
                    </div>
                    <div class="card-content">
                      <p>{{ item.content }}</p>
                      <small style="color: #ff6c37;">
                        <i class="el-icon-time"></i>
                        创建时间：{{ parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}') }}
                      </small>
                      <br>
                      <small style="color: #1ed76d;">
                        <i class="el-icon-time"></i>
                        已读时间：{{ parseTime(item.readTime, '{y}-{m}-{d} {h}:{i}') }}
                      </small>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
              <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
              />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <div v-show="false">
      <info-bell :refreshNoticeCount="isRefreshNoticeCount" />
    </div>
    
    
  </div>
</template>

<script>
import { listWbNoticeMessage,updateReadStatus} from "@/api/websocket/WbNoticeMessage"
import InfoBell from "@/components/InfoBell";

export default {
  name:"pushMesage",
  components: { InfoBell },
  data() {
    return {
      ws: null,
      message: '',
      messages: [],
      loading: true,
      total: 0,
      WbNoticeMessageList: [],
      form:{},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        type: null,
        senderId: null,
        senderName: null,
        receiverId: this.$store.state.user.id,
        receiverName: null,
        isRead: null,
        readTime: null,
        priority: null,
        targetUrl: null,
        bizType: null,
        bizId: null
      },
      activeName: 'unread',
      isRefreshNoticeCount:false,//是否刷新通知数量

    };
  },
  methods: {
    connectWebSocket() {
      // 连接 WebSocket，地址根据后端实际情况调整
      const currentUserId = this.$store.state.user.id;
      const currentUserNickName = this.$store.state.user.nickName;
      this.ws = new WebSocket(`ws://localhost:8080/websocket/pushMessage?userId=${currentUserId}&nickName=${currentUserNickName}`);

      this.ws.onopen = () => {
        console.log("推送信息-WebSocket 已连接");
        this.addMessage("推送信息-WebSocket 已连接");
      };

      this.ws.onmessage = event => {
        console.log("收到消息:", event.data);
        this.addMessage(event.data);
      };

      this.ws.onclose = () => {
        this.addMessage("推送信息-WebSocket 已关闭");
      };

      this.ws.onerror = error => {
        this.addMessage("推送信息-WebSocket 发生错误");
      };
    },
    sendMessage() {
      if (!this.form.content.trim()) {
        this.$message.warning("请输入消息内容");
        return;
      }
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        // 发送整个表单内容
        this.ws.send(JSON.stringify({
          data: this.form
        }));
        this.$message.success("消息发送成功");
        // 因为websocket发送请求是异步的，为了方便显示这里使用了延时，实际情况还是要在后端通过返回值来显示getList
        setTimeout(() => {
          this.getList();
        }, 500);
      } else {
        this.$message.error("WebSocket 未连接");
      }
      
    },
    addMessage(msg) {
      this.messages.push(msg);
      this.$nextTick(() => {
        // 自动滚动到底部
        const container = this.$el.querySelector("div[style*='overflow-y']");
        if (container) container.scrollTop = container.scrollHeight;
      });
    },
    /** --------------------------------- 信息模块 --------------------- */
    handleClick(){
      this.getList();
    },
    /** 查询通知信息框列表 */
    getList() {
      this.loading = true
      this.queryParams.isRead = this.activeName === 'unread' ? 0 : 1;
      console.log(this.queryParams);
      listWbNoticeMessage(this.queryParams).then(response => {
        this.WbNoticeMessageList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleUpdateReadStatus(row){
      if (row.id != null) {
        updateReadStatus(row.id).then(response => {
          this.isRefreshNoticeCount = true;
          if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({ type: "refresh" }));
          } else {
            this.$message.error("WebSocket 未连接");
          }
          this.$modal.msgSuccess("该信息已标记为已读~")

          this.getList();
        })
      }
    }
  },
  created() {
    this.getList();
  },
  mounted() {
    this.connectWebSocket();
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
  }
};
</script>

<style scoped>
.notice-card {
  margin-bottom: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title {
  font-weight: 600;
  font-size: 16px;
}
.card-content {
  margin-top: 5px;
}
.card-actions {
  text-align: right;
  margin-top: 10px;
}
</style>
